package beans

import (
	"encoding/json"
	"errors"
	"fmt"
	"time"

	"cn.xdns.monitor/monitor-client/util"
	"github.com/jinzhu/gorm"
)

type DnsProxyLog struct {
	Code               int        `gorm:"column:code"`
	CreateSysUserId    string     `gorm:"column:create_sys_user_id"`
	DnsProxyScheduleId string     `gorm:"column:dns_proxy_schedule_id"`
	ID                 string     `gorm:"column:id;primary_key"`
	IpAddr             string     `gorm:"column:ip_addr"`
	Isp                string     `gorm:"column:isp"`
	Msg                string     `gorm:"column:msg"`
	Port               int        `gorm:"column:port"`
	Prefix             string     `gorm:"column:prefix"`
	ServerName         string     `gorm:"column:server_name"`
	Speed              int64      `gorm:"column:speed"`
	Status             int        `gorm:"column:status"`
	Timeout            int        `gorm:"column:timeout"`
	UpdateSysUserId    string     `gorm:"column:update_sys_user_id"`
	Url                string     `gorm:"column:url"`
	Version            int        `gorm:"column:version"`
	CreateTime         *time.Time `gorm:"column:create_time"`
	UpdateTime         *time.Time `gorm:"column:update_time"`
	Page
}

func NewDnsProxyLog(code, port int, speed int64, status, timeout int, userId, dnsProxyScheduleId, isp, msg, pefix, serverName, url string) *DnsProxyLog {
	dnsProxyLog := &DnsProxyLog{
		Version:            0,
		Status:             status,
		Speed:              speed,
		Port:               port,
		Code:               code,
		Timeout:            timeout,
		CreateSysUserId:    userId,
		UpdateSysUserId:    userId,
		DnsProxyScheduleId: dnsProxyScheduleId,
		Isp:                isp,
		Msg:                msg,
		Prefix:             pefix,
		ServerName:         serverName,
		Url:                url,
	}
	return dnsProxyLog
}

// TableName sets the insert table name for this struct type
func (d *DnsProxyLog) TableName() string {
	return "tb_dns_proxy_log"
}

func (this DnsProxyLog) MarshalJSON() ([]byte, error) {
	type Alias DnsProxyLog
	data := &struct {
		UpdateTime string `json:"create_time"`
		CreateTime string `json:"update_time"`
		Alias
	}{
		UpdateTime: util.TimeFomat(this.UpdateTime),
		CreateTime: util.TimeFomat(this.CreateTime),
		Alias:      (Alias)(this),
	}
	return json.Marshal(data)
}

// 插入操作, 实现了事物控制
func (this *DnsProxyLog) Insert(db *gorm.DB) (res int64, err error) {
	return util.TX(db, nil, func(tx *gorm.DB) (i int64, err error) {
		now := time.Now()
		this.CreateTime = &now
		this.UpdateTime = &now

		this.Version = 1
		if needId := tx.NewRecord(this); needId {
			this.ID = util.UUID()
		}
		json.Marshal(*this)
		db := tx.Create(this)
		res = db.RowsAffected
		err = db.Error
		return res, err
	})
}

// 条件查询, 包含分页
func (this *DnsProxyLog) Select(data interface{}, db *gorm.DB) (res *[]interface{}, err error) {
	var selectAll = []DnsProxyLog{}
	this.Page.SetPage()
	db = db.Table((&DnsProxyLog{}).TableName()).Limit(this.Limit).Offset(this.Page.Page)

	if this.CreateTime != nil {
		db = db.Where("create_time >= ", this.CreateTime)
	}
	if this.UpdateTime != nil {
		db = db.Where("update_time >= ", this.UpdateTime)
	}
	if this.ID != "" {
		db = db.Where("id = ?", this.ID)
	}
	if this.DnsProxyScheduleId != "" {
		db = db.Where("dns_proxy_schedule_id = ?", this.DnsProxyScheduleId)
	}

	db = db.Order("create_time desc", true).Find(&selectAll)
	var r = []interface{}{}
	for _, v := range selectAll {
		v.Page = this.Page
		r = append(r, v)
	}

	return &r, db.Error
}

func (this *DnsProxyLog) SelectCountById(db *gorm.DB) (count int) {
	db = db.Raw("SELECT count(*) as count FROM `tb_dns_proxy_log` where dns_proxy_schedule_id = ?", this.DnsProxyScheduleId)
	db.Count(&count)
	//fmt.Println("=====> data is :", count)
	return
}

// 定时任务条件删除删除, !!! 若参数为空, 将清空整个表
func (this *DnsProxyLog) DeleteBeforeTime(db *gorm.DB) (res int64, err error) {
	return util.TX(db, nil, func(tx *gorm.DB) (res int64, err error) {
		fmt.Println("=====> I am in DeleteBeforeTime", )

		// 条件删除,
		if this != nil && this.CreateTime != nil {
			tx = tx.Where("create_time <= ?", this.CreateTime).Delete(DnsProxyLog{})
			res = tx.RowsAffected
			fmt.Printf("=====> deleted rows is : %v, condition less than or equal : %v \n", res, this.CreateTime.Format("2006-01-02T 15:04:05"))
			return res, tx.Error
		} else {
			return 0, errors.New("请选择您要删除的记录和过滤条件, 此方法无法删除全表数据!!!")
		}
	})
}
